import BaseHTTPServer
import os
import base64

USERNAME = 'admin'
PASSWORD = 'passw0rd_alert@cmp'
ALERT_DIR = '/home/appview/alert/'


def remove_lines(filepath, prefix):
    with open(filepath, 'r') as f:
        lines = f.readlines()

    with open(filepath, 'w') as f:
        for line in lines:
            if line.strip() == '' or line.startswith(prefix):
                continue
            f.write(line)


class RequestHandler(BaseHTTPServer.BaseHTTPRequestHandler):

    def do_GET(self):
        self.send_response(200)
        self.send_header('Content-type', 'text/html')
        self.end_headers()
        message = "Hello, world!"
        self.wfile.write(message)

    def do_POST(self):
        auth_header = self.headers.getheader('Authorization')
        if not auth_header:
            self.send_error(401, 'Authorization Required')
            return

        auth = auth_header.split(None, 1)[-1]
        auth = base64.b64decode(auth).decode()
        username, password = auth.split(':', 1)

        if username == USERNAME and password == PASSWORD:
            content_length = int(self.headers.getheader('content-length'))
            file_contents = self.rfile.read(content_length)
            file_path = ALERT_DIR + self.path
            with open(file_path, 'wb') as f:
                f.write(file_contents)
            remove_lines(file_path, '-')
            remove_lines(file_path, 'Content-')
            self.send_response(200)
            self.send_header('Content-type', 'text/html')
            self.end_headers()
            message = "File uploaded successfully"
            self.wfile.write(message)
        else:
            self.send_error(401, 'Authorization Required')


if __name__ == '__main__':
    server_address = ('', 8089)
    httpd = BaseHTTPServer.HTTPServer(server_address, RequestHandler)
    print('Starting server at http://localhost:8089')
    httpd.serve_forever()